package com.weizai.carshop.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weizai.carshop.common.enumeration.AppHttpCodeEnum;
import com.weizai.carshop.common.properties.JwtProperties;
import com.weizai.carshop.common.result.ResponseResult;
import com.weizai.carshop.common.utils.JwtUtil;
import com.weizai.carshop.mapper.LoginMapper;
import com.weizai.carshop.model.entiity.AppUserEntity;
import com.weizai.carshop.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class AppUserServiceImpl extends ServiceImpl<LoginMapper, AppUserEntity> implements AppUserService {

    @Autowired
    private JwtProperties jwtProperties;

    /*
     * 登录接口
     * */
    @Override
    public ResponseResult login(String username, String password) {
        // 查询数据库是否有账号
        AppUserEntity user = lambdaQuery()
                .eq(AppUserEntity::getUsername, username)
                .one();

        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USERNAME_ERROR);
        }

        System.out.println(DigestUtil.md5Hex(password));
        // 判断密码是否正确
        if (!DigestUtil.md5Hex(password).equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PASSWORD_ERROR);
        }
        user.setPassword("****");
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        claims.put("username", user.getUsername());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        user.setToken(jwt);
        return ResponseResult.okResult(user);
    }


    /*
     * 更新收藏方法
     * */
    @Override
    public String updateCollect(Long collectId, Long userId) {

        // 查询用户信息
        AppUserEntity user = lambdaQuery().eq(AppUserEntity::getId, userId).one();

        String collectList = user.getCollectList();

        // 判断收藏列表是否为空
        if (collectList.isEmpty()) {
            user.setCollectList(collectId.toString());
            updateById(user);
            return collectId.toString();
        }

        // 收藏列表不为空请情况
        ArrayList<String> list = Arrays.stream(collectList.split(",")).collect(Collectors.toCollection(() -> new ArrayList<>()));
        String substring;
        if (list.contains(collectId.toString())) {
            list.remove(collectId.toString());
            substring = getString(list);
        } else {
            list.add(collectId.toString());
            Collections.sort(list);
            substring = getString(list);
        }
        user.setCollectList(substring);
        updateById(user);
        return substring;
    }


    private static String getString(ArrayList<String> list) {
        StringBuilder stringBuilder = new StringBuilder();
        list.forEach(string -> stringBuilder.append(string).append(","));
        String substring = stringBuilder.substring(0, list.size() >= 1 ? stringBuilder.length() - 1 : 0);
        return substring;
    }
}
